<?php
/**
 * Created by PhpStorm.
 * User: 毛文科
 * Date: 2019/5/21
 * Time: 13:20
 */
namespace app\admin\controller;
use app\admin\model\DiGui;
use app\admin\model\Enclosure;
use app\admin\model\Functions;
use app\admin\model\Jurisdiction;
use app\admin\model\Models;
use app\admin\model\Mokuais;
use app\admin\model\Subject;
use app\admin\model\System;
use app\admin\model\Users;
use think\Controller;
use think\Db;
use think\Request;
use tp5er\Backup;

class Index extends Controller
{
    /**加载cms首页
     * @param Request $request
     * @return mixed|\think\response\Redirect
     */
    public function index(Request $request){
        if(!session('modular')){
            return redirect('index/modular');
        }
        if(!$user = session('adminuser')){
            return redirect('index/signin');
        }
//        Subject::addFangwen();
        //添加用户信息
        $this->assign('user',$user);
        $mokuai = Mokuais::where('status',1)->select()->toArray();
        foreach ($mokuai as $key=>$value){
            $mokuai[$key]['column'] = DiGui::getColumn('column',$value['id']);
        }
        $this->assign('mokuai',$mokuai);
        $lianbiao = Models::where('status',1)
            ->where('model_type','联表模型')
            ->select()
            ->toArray();
        $this->assign('lianbiao',$lianbiao);
        return $this->fetch();
    }

    /**加载登录页面
     * @param Request $request
     * @return mixed
     */
    public function signin(Request $request){
        $str = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents("./static/home/fuwenben/php/config.json")), true);
        foreach ($str as $key=>$value){
            if($key=='imagePathFormat'||$key=='scrawlPathFormat'||$key=='snapscreenPathFormat'||$key=='catcherPathFormat'){
                $value = '/uploads/'.session('modular').'/image/{yyyy}{mm}{dd}/{time}{rand:6}';
            }
            if($key=='videoPathFormat'){
                $value = '/uploads/'.session('modular').'/video/{yyyy}{mm}{dd}/{time}{rand:6}';
            }
            if($key=='filePathFormat'){
                $value = '/uploads/'.session('modular').'/file/{yyyy}{mm}{dd}/{time}{rand:6}';
            }
            if($key=='imageManagerListPath'){
                $value = '/uploads/'.session('modular').'/image/';
            }
            if($key=='fileManagerListPath'){
                $value = '/uploads/'.session('modular').'/file/';
            }
            $str[$key] = $value;
        }
        chmod("./static/home/fuwenben/php/config.json",0777);
        file_put_contents("./static/home/fuwenben/php/config.json",json_encode($str));
        $data = $request->param();
        if(isset($data['modular'])&&$data['modular']){
            session('modular',$data['modular']);
        }
        return $this->fetch();
    }

    /**加载模块选择页面
     * @return mixed
     */
    public function modular(){
        session('adminuser',null);
        session('modular',null);
        $dir = Functions::getDirList('../application',['admin']);
        $modular = config('modular.');
//        echo '<pre>';print_r($modular);exit;
        $this->assign('dir',$dir);
        $this->assign('modular',$modular);
        return $this->fetch();
    }
    /**加载欢迎页面
     * @return mixed
     */
    public function welcome(){
        $fangwenliangs = System::where('name|en_name','fangwen')->findOrEmpty()->toArray();
        $fangwenliang = 0;
        if($fangwenliangs){
            $fangwenliang = (int)$fangwenliangs['value'];
        }
        $fujianliang = Enclosure::where('id','>',0)->count();
        $yonghuliang = Users::where('id','>',0)->count();
        $this->assign('fangwen',$fangwenliang);
        $this->assign('fujian',$fujianliang);
        $this->assign('yonghu',$yonghuliang);
        return $this->fetch();
    }
    public function errors($code,$action=null){
        $this->assign('code',$code);
        $this->assign('action',trim(urldecode($action),'/'));
        return $this->fetch('public/error');
    }
    public function out(){
        session('adminuser',null);
        return redirect('index/signin');
    }
    public function add(){
        return NewBuilder::make('form')
            ->addAction('index/project')
            ->addInput('name','项目名称')
            ->addInput('dir','项目模块')
            ->addInput('author','作者')
            ->addInput('sql','数据库文件')
            ->addInput('img','图片地址','/static/home/img/error.jpg')
            ->addFormButton('submit','提交')
            ->addFormButton('back','返回')
            ->fetch();
    }
    public function project(Request $request){
        $data = $request->param();
        $modular = config('Modular.');
        foreach ($modular as $value){
            if($value['dir']==$data['dir']){
                echo '此模块已存在';
                exit;
            }
        }
        $modular = array_merge($modular,[$data]);
        if(Functions::changeConfig('../config/Modular.php',$modular)){
            return redirect('index/errors',['code'=>200]);
        }else{
            return redirect('index/errors',['code'=>205]);
        }
    }

    /**备份函数
     * @param Request $request
     * @return \think\response\Redirect
     */
    public function beifen(Request $request){
        $data = $request->param();
        if(Subject::beifen($data)){
            return redirect('index/errors',['code'=>200]);
        }else{
            return redirect('index/errors',['code'=>205]);
        }
        $config = [
            'path'=>'./Data/'
        ];
        $db = new Backup($config);
        $files = $db->dataList();
        $zhenze = '/'.config('database.prefix').session('modular').'_/';
        $newfiles = [];
        foreach ($files as $value){
            if(preg_match($zhenze,$value['name'])){
                $newfiles[] = $value;
            }
        }
        $name = session('modular').'_'.time();
        foreach ($files as $value){
            $db->setFile(['name'=>$name,'part'=>1])->backup($value['name'],0);
        }
        $data['path'] = '/Data/'.$name.'-1.sql';
        $data['name'] = $name.'-1.sql';
        $data['create_time'] = time();
        Db::name(session('modular').'_database_system')->where('id',3)->update(['value'=>time()]);
        if(Db::name(session('modular').'_databases')->insert($data)){
            return redirect('index/errors',['code'=>200]);
        }else{
            return redirect('index/errors',['code'=>205]);
        }
    }

    /**还原数据
     * @param Request $request
     * @return \think\response\Json
     */
    public function huanyuan(Request $request){
        $id = $request->param('id',null);
        $sql = $request->param('sql',null);
        if(Subject::huanyuan(['id'=>$id,'sql'=>$sql])){
            return json_my_response('还原成功',200);
        }else{
            return json_my_response('还原失败',205);
        }
        return json_my_response('成功',200);
    }

    /**自动备份接口
     * @return \think\response\Json
     */
    public function zidongbeifen(){
        $system = Db::name(session('modular').'_database_system')
            ->where('name','自动备份')
            ->find();
        if(!$system){
            return json_my_response('没有开启自动备份');
        }
        if((int)$system['value']==0){
            return json_my_response('没有开启自动备份');
        }
        $tian = Db::name(session('modular').'_database_system')
            ->where('name','自动备份间隔(天)')
            ->find();
        if($tian['value']==0){
            return json_my_response('起码设置一天备份');
        }
        $zuihou = Db::name(session('modular').'_database_system')
            ->where('name','上次备份时间')
            ->find();
        if(time()<((int)$tian['value']*24*3600+(int)$zuihou['value'])){
            return json_my_response('备份时间未道');
        }
        Subject::beifen(['remarks'=>'自动备份']);
        return json_my_response('备份成功',200);
    }

    /**中间件
     * @param $request
     * @param \Closure $next
     * @return mixed|\think\response\Redirect
     */
    public function handle($request,\Closure $next){
        $modular = $request->param('modular',null);
        $cid     = $request->param('cid',null);
        $model_id = $request->param('model_id',null);
        if($cid){
            session('cid',$cid);
        }
        if($model_id){
            session('model_id',$model_id);
        }
        if($modular){
            session('modular',$modular);
            if($request->controller()=='index'&&$request->action()=='index'){
                if(!session('adminuser')){
                    return redirect('index/signin');
                }
            }
        }
        if(session('modular')&&session('adminuser')){
            Jurisdiction::inspect($request);
        }
        $api = new Api();
        if(!$api->souquan($request)){
            if(\request()->isAjax()){
                return json_my_response('网站未授权');
            }else{
                echo  '网站未授权';exit;
            }
        }
        return $next($request);
    }
}